import {ToM, SnakeCase, CamelCase} from "@/schemas/base.ts";

const camelCase = <T extends string>(s: T): CamelCase<T> => {
    return s.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase()) as CamelCase<T>;
}

const snakeCase = <T extends string>(s: T): SnakeCase<T> => {
    return s.replace(/([A-Z])/g, (_, c) => `_${c.toLowerCase()}`) as SnakeCase<T>;
}

/// 数据库model转化为表单Schema，多用于查询
export const mToS = <T>(data: any): T => {
    const result: { [k: string]: any } = {};
    if (Array.isArray(data)) {
         return data.map(i => mToS(i)) as T;
    }
    for (const key of Object.keys(data)) {
        const camelCaseKey = camelCase(key)
        if (Array.isArray(data[key])) {
            result[camelCaseKey] = data[key].map(i => mToS(i));
        } else if (data[key] && typeof data[key] === "object") {
            result[camelCaseKey] = mToS(data[key]); // 递归转换
        } else {
            result[camelCaseKey] = data[key];
        }
    }
    return result as T
}

/// 表单Schema转化为数据库model，多用于增删改
export const sToM = <T extends { [k: string]: any }>(data: T): ToM<T> => {
    const result: { [k: string]: any } = {};
    for (const key of Object.keys(data)) {
        const camelCaseKey = snakeCase(key)
        if (Array.isArray(data[key])) {
            result[camelCaseKey] = data[key].map(i => sToM(i));
        } else if (data[key] && typeof data[key] === "object") {
            result[camelCaseKey] = sToM(data[key]); // 递归转换
        } else {
            result[camelCaseKey] = data[key];
        }
    }
    return result as ToM<T>
}